<template>
  <div class="event-edit-container">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑活动' : '添加活动' }}</h2>
      <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
    </div>

    <div class="form-container">
      <el-form 
        ref="formRef" 
        :model="eventForm" 
        :rules="rules" 
        label-width="100px"
        v-loading="loading"
      >
        <!-- 表单内容 -->
        <el-form-item label="活动名称" prop="title">
          <el-input v-model="eventForm.title" placeholder="请输入活动名称" maxlength="100" show-word-limit />
        </el-form-item>
        
        <el-form-item label="活动封面" prop="cover">
          <el-upload
            class="avatar-uploader"
            action=""
            :http-request="uploadCover"
            :show-file-list="false"
            :before-upload="beforeCoverUpload"
          >
            <img 
              v-if="eventForm.cover" 
              :src="displayImage(eventForm.cover)" 
              class="cover-image" 
              @error="handleImageError"
            />
            <div v-else-if="imageError" class="image-error">
              <el-icon><Picture /></el-icon>
              <span>图片加载失败</span>
            </div>
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            <p>支持JPG、PNG格式，建议尺寸800x400像素，大小不超过2MB</p>
          </div>
        </el-form-item>
        
        <el-form-item label="活动状态" prop="status">
          <el-select v-model="eventForm.status" placeholder="请选择活动状态" class="form-select">
            <el-option label="草稿" value="draft">
              <span style="color: #909399;">草稿</span>
            </el-option>
            <el-option label="已上线" value="online">
              <span style="color: #67C23A;">已上线</span>
            </el-option>
            <el-option label="已下线" value="offline">
              <span style="color: #F56C6C;">已下线</span>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="eventForm.location" placeholder="请输入活动地点" />
        </el-form-item>
        
        <el-form-item label="活动时间" prop="startTime">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleTimeChange"
          />
        </el-form-item>
        
        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="eventForm.description"
            type="textarea"
            placeholder="请输入活动描述"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="活动分类" prop="category">
          <el-select v-model="eventForm.category" placeholder="请选择活动分类" class="form-select">
            <el-option label="音乐" value="音乐" />
            <el-option label="讲座" value="讲座" />
            <el-option label="亲子" value="亲子" />
            <el-option label="展览" value="展览" />
            <el-option label="戏剧" value="戏剧" />
            <el-option label="运动" value="运动" />
            <el-option label="公益" value="公益" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">{{ isEdit ? '保存修改' : '创建活动' }}</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button v-if="isEdit" type="success" @click="showQuestionnaireDialog">添加问卷</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 问卷模板选择对话框 -->
    <el-dialog
      v-model="questionnaireSelectDialogVisible"
      title="选择问卷模板"
      width="60%"
      append-to-body
    >
      <div class="dialog-content">
        <div class="dialog-tip">
          可以选择多个问卷模板进行关联
        </div>
        <div class="search-box">
          <el-input
            v-model="questionnaireSearchText"
            placeholder="搜索问卷标题"
            clearable
            @clear="fetchQuestionnaires"
          >
            <template #append>
              <el-button @click="fetchQuestionnaires">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
        <el-table 
          :data="questionnaireList" 
          border 
          style="width: 100%" 
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="问卷标题" min-width="180" show-overflow-tooltip />
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="creatorName" label="创建人" width="120" show-overflow-tooltip />
          <el-table-column prop="createdAt" label="创建时间" width="160" show-overflow-tooltip />
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="questionnaireSelectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="associateQuestionnaires" :loading="associating">
            关联选中问卷
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Plus, UploadFilled, Picture, Search } from '@element-plus/icons-vue'
import { getEventDetail, createEvent, updateEvent, uploadEventCover } from '@/api/event'
import { getFullImageUrl, addCacheBuster, removeQueryParams } from '@/utils/imageHelper'
import { getQuestionnaireTemplates, associateEventQuestionnaires } from '@/api/questionnaire'

// 路由对象和路由实例
const route = useRoute()
const router = useRouter()
const formRef = ref(null)

// 判断是编辑还是新增
const isEdit = computed(() => !!route.params.id)
// 活动ID
const eventId = computed(() => route.params.id)

// 加载状态和提交状态
const loading = ref(false)
const submitting = ref(false)
const imageError = ref(false)

// 活动时间范围
const timeRange = ref([])

// 表单数据
const eventForm = reactive({
  title: '',
  status: 'draft',
  location: '',
  startTime: '',
  endTime: '',
  description: '',
  notes: '',
  cover: '',
  category: '',
  tags: ''
})

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择活动状态', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择活动时间范围', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' }
  ],
  cover: [
    { required: true, message: '请上传活动封面', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择活动分类', trigger: 'change' }
  ],
  notes: [
    { required: false, message: '请输入活动须知', trigger: 'blur' }
  ]
}

// 时间范围变化处理
const handleTimeChange = (val) => {
  console.log('时间范围变化:', val)
  if (val && val.length === 2) {
    eventForm.startTime = val[0]
    eventForm.endTime = val[1]
  } else {
    eventForm.startTime = ''
    eventForm.endTime = ''
  }
}

// 页面加载时，如果是编辑模式则获取活动详情
onMounted(async () => {
  if (isEdit.value) {
    await fetchEventDetail()
  }
})

// 获取活动详情
const fetchEventDetail = async () => {
  loading.value = true
  imageError.value = false
  try {
    const res = await getEventDetail(eventId.value)
    if (res.code === 200) {
      // 填充表单数据
      Object.assign(eventForm, res.data)
      
      // 处理封面路径 - 确保使用网关访问
      if (eventForm.cover) {
        eventForm.cover = getFullImageUrl(eventForm.cover)
        console.log('处理后的图片回显路径:', eventForm.cover)
      }
      
      // 设置时间范围
      timeRange.value = [eventForm.startTime, eventForm.endTime]
    } else {
      ElMessage.error(res.msg || '获取活动详情失败')
    }
  } catch (error) {
    console.error('获取活动详情异常:', error)
    ElMessage.error('获取活动详情失败')
  } finally {
    loading.value = false
  }
}

// 处理图片加载错误
const handleImageError = (e) => {
  console.error('图片加载失败:', e)
  imageError.value = true
  
  // 检查是否已经尝试过重新加载
  if (eventForm.cover && eventForm.cover.includes('?') && !e.target.hasAttribute('data-retried')) {
    // 标记已经尝试过重新加载
    e.target.setAttribute('data-retried', 'true')
    
    // 尝试不带缓存参数重新加载
    const baseUrl = eventForm.cover.split('?')[0]
    console.log('尝试不带缓存参数重新加载:', baseUrl)
    e.target.src = baseUrl
  }
}

// 封面上传前检查
const beforeCoverUpload = (file) => {
  imageError.value = false
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('封面图片只能是JPG或PNG格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('封面图片大小不能超过2MB!')
    return false
  }
  return true
}

// 处理图片显示
const displayImage = (path) => {
  return addCacheBuster(getFullImageUrl(path))
}

// 上传封面
const uploadCover = async (params) => {
  const file = params.file
  
  try {
    loading.value = true
    imageError.value = false
    
    const res = await uploadEventCover(file)
    
    if (res.code === 200) {
      console.log('后端返回的原始数据:', res.data)
      
      // 提取图片路径
      let imagePath = '';
      if (typeof res.data === 'object' && res.data !== null) {
        imagePath = res.data.url || '';
      } else if (typeof res.data === 'string') {
        imagePath = res.data;
      }
      
      // 确保通过getFullImageUrl处理路径
      eventForm.cover = getFullImageUrl(imagePath);
      console.log('图片上传成功，完整URL路径:', eventForm.cover);
      ElMessage.success('封面上传成功');
    } else {
      ElMessage.error(res.msg || '封面上传失败');
      imageError.value = true;
    }
  } catch (error) {
    console.error('上传封面异常:', error);
    ElMessage.error('封面上传失败');
    imageError.value = true;
  } finally {
    loading.value = false;
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  // 确保时间数据已正确设置
  if (!eventForm.startTime || !eventForm.endTime) {
    ElMessage.warning('请选择活动时间范围')
    return
  }
  
  // 确保必填字段都已填写
  if (!eventForm.cover) {
    ElMessage.warning('请上传活动封面')
    return
  }
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 移除查询参数
        let coverPath = removeQueryParams(eventForm.cover);
        
        // 如果是完整URL，提取路径部分
        if (coverPath.startsWith('http://') || coverPath.startsWith('https://')) {
          try {
            const url = new URL(coverPath);
            coverPath = url.pathname; // 提取路径部分
          } catch (e) {
            console.error('URL解析失败:', e);
          }
        }
        
        // 将分类值同时赋值给标签字段
        eventForm.tags = eventForm.category;
        
        // 不需要再进行复杂的路径转换
        console.log('提交前的图片路径:', coverPath);
        console.log('提交前的表单数据:', eventForm);
        
        // 复制表单数据，避免直接修改reactive对象
        const formData = { ...eventForm, cover: coverPath }
        
        let res
        if (isEdit.value) {
          // 编辑模式
          res = await updateEvent(eventId.value, formData)
        } else {
          // 新增模式
          res = await createEvent(formData)
        }
        
        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '活动更新成功' : '活动创建成功')
          // 跳转回列表页
          router.push('/event')
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('提交表单错误:', error)
        ElMessage.error('操作失败')
      } finally {
        submitting.value = false
      }
    } else {
      // 打印出哪些字段验证未通过
      const invalidFields = formRef.value.fields.filter(field => field.validateState === 'error')
      console.error('表单验证失败的字段:', invalidFields.map(f => f.prop))
      ElMessage.warning('请完善表单信息')
      return false
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    if (!isEdit.value) {
      timeRange.value = []
    } else {
      // 编辑模式下重置为原始数据
      timeRange.value = [eventForm.startTime, eventForm.endTime]
    }
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 问卷模板相关
const questionnaireSelectDialogVisible = ref(false)
const questionnaireList = ref([])
const selectedQuestionnaires = ref([])
const loadingQuestionnaires = ref(false)
const associating = ref(false)
const questionnaireSearchText = ref('')
const questionnairePage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 显示问卷选择对话框
const showQuestionnaireDialog = () => {
  questionnaireSelectDialogVisible.value = true
  fetchQuestionnaires()
}

// 获取问卷模板列表
const fetchQuestionnaires = async () => {
  if (!eventId.value) {
    ElMessage.warning('请先保存活动')
    questionnaireSelectDialogVisible.value = false
    return
  }
  
  loadingQuestionnaires.value = true
  try {
    const res = await getQuestionnaireTemplates({
      pageNum: questionnairePage.current,
      pageSize: questionnairePage.size,
      keyword: questionnaireSearchText.value
    })
    if (res.code === 200 && res.data) {
      questionnaireList.value = res.data.records || res.data.list || res.data
      questionnairePage.total = res.data.total || res.data.length || 0
    } else {
      ElMessage.error(res.msg || '获取问卷模板列表失败')
    }
  } catch (error) {
    console.error('获取问卷模板列表异常:', error)
    ElMessage.error('获取问卷模板列表失败')
  } finally {
    loadingQuestionnaires.value = false
  }
}

// 处理问卷模板选择
const handleQuestionnaireSelect = (row) => {
  selectedQuestionnaires.value = [row]
}

// 处理多选变化
const handleSelectionChange = (selection) => {
  selectedQuestionnaires.value = selection
}

// 关联所选问卷模板
const associateQuestionnaires = async () => {
  if (selectedQuestionnaires.value.length === 0) {
    ElMessage.warning('请至少选择一个问卷模板')
    return
  }
  
  associating.value = true
  try {
    const templateIds = selectedQuestionnaires.value.map(item => item.id)
    const res = await associateEventQuestionnaires(eventId.value, templateIds)
    
    if (res.code === 200) {
      ElMessage.success(`成功关联${selectedQuestionnaires.value.length}个问卷模板`)
      questionnaireSelectDialogVisible.value = false
      
      // 显示关联结果统计
      const { totalCount, successCount, details } = res.data || {}
      if (totalCount && successCount) {
        if (totalCount === successCount) {
          ElMessage.success(`成功关联全部${totalCount}个问卷模板`)
        } else {
          ElMessage.warning(`成功关联${successCount}/${totalCount}个问卷模板`)
        }
      }
    } else {
      ElMessage.error(res.msg || '关联问卷模板失败')
    }
  } catch (error) {
    console.error('关联问卷模板异常:', error)
    ElMessage.error('关联问卷模板失败')
  } finally {
    associating.value = false
  }
}
</script>

<style scoped>
.event-edit-container {
  animation: fadeIn 0.3s ease-out;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: var(--card-background);
  padding: 20px 24px;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: var(--text-primary);
  display: flex;
  align-items: center;
}

.page-header h2::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 20px;
  background: linear-gradient(180deg, var(--primary-color), #4d7aff);
  margin-right: 12px;
  border-radius: 2px;
}

.form-container {
  background-color: var(--card-background);
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
  padding: 30px;
}

.form-select {
  width: 100%;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 300px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 150px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-image {
  width: 300px;
  height: 150px;
  display: block;
  object-fit: cover;
}

.image-error {
  width: 300px;
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.upload-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 8px;
}

.form-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.dialog-tip {
  margin-bottom: 10px;
  color: #909399;
  font-size: 14px;
}

.search-box {
  margin-bottom: 15px;
}
</style> 